package com.geek.base.system.service.impl;

import com.geek.base.system.bean.SysRole;
import com.geek.base.system.bean.SysRoleMenu;
import com.geek.base.system.dao.SysRoleMapper;
import com.geek.base.system.service.SysRoleService;
import com.geek.tool.KeyGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @功能 系统菜单业务实现
 * @作者 MaxBill
 * @时间 2018年7月29日
 * @邮箱 maxbill1993@163.com
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    public int insertRole(SysRole record) {
        return this.sysRoleMapper.insert(record);
    }

    public int updateRole(SysRole record) {
        return this.sysRoleMapper.update(record);
    }

    @Transactional
    public int deleteRole(String roleId) {
        int delFlag = this.sysRoleMapper.delete(roleId);
        if (delFlag == 1) {
            this.sysRoleMapper.deleteRoleMenu(roleId);
        }
        return delFlag;
    }

    public SysRole selectRoleByRoleId(String roleId) {
        return this.sysRoleMapper.selectRoleByRoleId(roleId);
    }

    public SysRole selectRoleByUserId(String userId) {
        return this.sysRoleMapper.selectRoleByUserId(userId);
    }

    public List<SysRole> selectRoleList(SysRole record) {
        return this.sysRoleMapper.selectRoleList(record);
    }

    @Transactional
    public boolean configRole(String roleId, String roleMenu) {
        try {
            String[] menuIdArray = roleMenu.split(",", -1);
            this.sysRoleMapper.deleteRoleMenu(roleId);
            if (null != menuIdArray && menuIdArray.length > 0) {
                for (String menuId : menuIdArray) {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRmId(KeyGeneratorUtil.getUUIDKey());
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setCreateTime(new Date());
                    this.sysRoleMapper.config(sysRoleMenu);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
